package com.jinsilu.freight.ui.activity;

import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyVBActivity;
import com.jinsilu.freight.databinding.ActivityUploadQualificationCertificateBinding;
import com.jinsilu.freight.helper.ShowImageHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.GetQualificationsApi;
import com.jinsilu.freight.http.request.UpdateImageApi;
import com.jinsilu.freight.http.request.VerifyQualificationApi;
import com.jinsilu.freight.http.response.FileBean;
import com.jinsilu.freight.http.response.QualificationsBean;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.dialog.DateDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 上传从业资格证
 *
 * @author yangyang
 * @time 2020-11-11 17:35
 */
public class UploadQualificationCertificateActivity
        extends MyVBActivity<ActivityUploadQualificationCertificateBinding> {

    private final String TAG = getClass().getName();

    private String picUrl;

    private QualificationsBean mQualificationsBean;

    @Override
    protected void initView() {
        // binding.tvNotificationTips.setVisibility(View.VISIBLE);
        // binding.tvNotificationTips.setText("拍摄图片时，请保持画面文字的清晰。");

        setOnClickListener(
                binding.ivQualificationPhoto,
                binding.tvBtnSubmitCertificate,
                binding.tvValidStartDate,
                binding.tvValidEndDate);

    }

    @Override
    protected void initData() {
        getQualificationStatus();
        initStep();
    }

    private void initStep() {
        binding.layoutCertification.tvCertificationTips.setText("请使用本人身份信息进行认证，若使用他人身份认证并接单，将造成运费无法提现");
        binding.tvCheckTheInformation.setText(Html.fromHtml(getString(R.string.tips_qualification_certificate)));
        binding.layoutCertification.stepView.go(MTLConstants.STEP_THREE, true);
    }

    /**
     * 获取从业资格证状态
     */
    private void getQualificationStatus() {
        EasyHttp.get(this)
                .api(new GetQualificationsApi())
                .request(new HttpCallback<HttpData<QualificationsBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<QualificationsBean> data) {
                        mQualificationsBean = data.getData();
                        setCertificateStatus(mQualificationsBean);
                    }
                });
    }

    private void setCertificateStatus(QualificationsBean qualificationsBean) {
        switch (qualificationsBean.getProfessionalQualificationCertificateStatus()) {
            case -2: // 未认证
                if (!TextUtils.isEmpty(qualificationsBean.getProfessionalQualificationNumber()))
                    binding.etQualificationNumber.setText(qualificationsBean.getProfessionalQualificationNumber());
                break;
            case 0: // 认证失败
                // binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_rejected_ic);
                // binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
                // binding.layoutCertification.tvCertificationStatus.setText("审核未通过");
                // binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                binding.layoutCertification.tvCertificationTips.setText(
                        TextUtils.isEmpty(qualificationsBean.getOpinion()) ? "" : qualificationsBean.getOpinion());
                setContentData(qualificationsBean);
                break;
            case 1: // 认证成功
                // binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approved_ic);
                // binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
                // binding.layoutCertification.tvCertificationStatus.setText("审核通过");
                // binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approved));
                setContentData(qualificationsBean);
                break;
            case -1: // 提交全部认证资料 认证中
                // binding.layoutCertification.ivCertificationResult.setImageResource(R.drawable.approving_ic);
                // binding.layoutCertification.ivCertificationResult.setVisibility(View.VISIBLE);
                // binding.layoutCertification.tvCertificationStatus.setText("审核中");
                // binding.layoutCertification.tvCertificationStatus.setVisibility(View.VISIBLE);
                disableClicked(getString(R.string.tips_approving));
                setContentData(qualificationsBean);
                break;
            default:
                break;
        }
    }

    /**
     * 设置不允许点击
     */
    private void disableClicked(String tips) {
        binding.ivQualificationPhoto.setEnabled(false);
        binding.etQualificationNumber.setEnabled(false);
        binding.tvValidStartDate.setEnabled(false);
        binding.tvValidEndDate.setEnabled(false);

        binding.layoutCertification.stepView.done(true);

        binding.layoutCertification.tvCompleteCanTakeOrder.setText(tips);
        binding.layoutCertification.tvCertificationTips.setVisibility(View.GONE);

        binding.tvQualificationTips.setVisibility(View.GONE);

    }

    /**
     * 数据回填
     *
     * @param qualificationsBean 寸业证信息
     */
    private void setContentData(QualificationsBean qualificationsBean) {
        picUrl = qualificationsBean.getProfessionalQualification();
        if (!TextUtils.isEmpty(picUrl))
            ShowImageHelper.showNormal(this, qualificationsBean.getProfessionalQualification(),
                    binding.ivQualificationPhoto);
        binding.etQualificationNumber.setText(qualificationsBean.getProfessionalQualificationNumber());
        binding.tvValidStartDate.setText(qualificationsBean.getValidStartDate());
        binding.tvValidEndDate.setText(qualificationsBean.getValidEndDate());
        binding.tvBtnSubmitCertificate.setEnabled(true);
    }

    @Override
    public void onClick(View v) {
        if (v == binding.ivQualificationPhoto) {
            // startImageSelectActivity(0);
            showTipsDialog();
        } else if (v == binding.tvBtnSubmitCertificate) {
            if (null == mQualificationsBean) {
                toast(R.string.error_certification_failed_with_network);
                return;
            }
            switch (mQualificationsBean.getProfessionalQualificationCertificateStatus()) {
                // -2---未认证，-1---待审核，0---失败，1---成功
                case -2: // 未认证
                case 0: // 认证失败
                    submitInfo();
                    break;
                case -1: // -待审核
                case 1: // 认证成功
                    toNextSteps();
                    break;
                default:
                    break;
            }
        } else if (v == binding.tvValidStartDate) {
            showDateDialog(0);
        } else if (v == binding.tvValidEndDate) {
            showDateDialog(1);
        }
    }

    private BaseDialog expirationDialog;

    private void showDateDialog(int type) {
        // 日期选择对话框
        new DateDialog.Builder(this)
                .setTitle(getString(R.string.date_title))
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(getString(R.string.common_cancel))
                .setListener(new DateDialog.OnListener() {
                    @Override
                    public void onSelected(BaseDialog dialog, int year, int month, int day) {
                        if (type == 0) {
                            binding.tvValidStartDate.setText(String.format("%s-%s-%s", year, month, day));
                        } else if (type == 1) {
                            binding.tvValidEndDate.setText(String.format("%s-%s-%s", year, month, day));
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                    }
                })
                .show();
    }

    private BaseDialog tipsDialog;

    private void showTipsDialog() {
        // 自定义对话框
        if (null == tipsDialog) {
            tipsDialog = new BaseDialog.Builder(this)
                    .setContentView(R.layout.dialog_certificate_tips)
                    .setAnimStyle(BaseDialog.ANIM_SCALE)
                    // .setText(id, "我是预设置的文本")
                    .setGravity(Gravity.BOTTOM)
                    .setOnClickListener(R.id.tv_know, (BaseDialog.OnClickListener<TextView>) (dialog, view) -> {
                        // showMenuDialog();
                        startImageSelectActivity(-1);
                        dialog.dismiss();
                    }

                    )
                    .show();
        } else {
            tipsDialog.show();
        }
    }

    /**
     * 身份验证
     */
    private void submitInfo() {
        if (TextUtils.isEmpty(picUrl)) {
            toast("请上传从业资格证");
            return;
        }
        String qualificationNumber = binding.etQualificationNumber.getText().toString().trim();
        if (TextUtils.isEmpty(qualificationNumber)) {
            toast("请输入从业资格证号");
            return;
        }

        String validStartDate = binding.tvValidStartDate.getText().toString().trim();
        String validEndDate = binding.tvValidEndDate.getText().toString().trim();

        EasyHttp.post(this)
                .api(new VerifyQualificationApi()
                        .setProfessionalQualificationUrl(picUrl)
                        .setProfessionalQualificationNumber(qualificationNumber)
                        .setValidStartDate(validStartDate)
                        .setValidEndDate(validEndDate))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        // setResult(RESULT_OK);
                        // finish();
                        toNextSteps();
                    }
                });
    }

    private void toNextSteps() {
        startActivity(UploadVehicleLicenseActivity.class);
    }

    /**
     * 启动图片选择
     */
    private void startImageSelectActivity(int index) {
        ImageSelectVBActivity.start(this, new ImageSelectVBActivity.OnPhotoSelectListener() {

            @Override
            public void onSelected(File file) {
                // File file = CommonHelper.getFileFromUri(data);
                uploadImage(file);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void uploadImage(File file) {
        // 上传文件
        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setImage(file))
                .request(new HttpCallback<HttpData<FileBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<FileBean> data) {
                        // FileUtils.delete(file);
                        String imgUrl = data.getData().getUrl();
                        picUrl = imgUrl;
                        ShowImageHelper.showNormal(UploadQualificationCertificateActivity.this, imgUrl,
                                binding.ivQualificationPhoto);
                    }
                });
    }
}
